<template>
  <div>
  <el-card class="content-wrap">
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="职业编码" prop="professionCode">
        <el-input
          v-model="queryParams.professionCode"
          placeholder="请输入职业编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="职业名称" prop="professionName">
        <el-input
          v-model="queryParams.professionName"
          placeholder="请输入职业名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="职业大类" prop="professionCategory">
        <el-input
          v-model="queryParams.professionCategory"
          placeholder="请输入职业大类"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="approvalStatus">
        <el-select
          v-model="queryParams.approvalStatus"
          placeholder="请选择审核状态"
          clearable
          class="!w-240px"
        >
          <el-option label="待审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="未通过" :value="2" />
          <el-option label="审核中" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:profession:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:profession:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 列表 -->
  <el-card class="content-wrap">
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="职业编码" align="center" prop="professionCode" />
      <el-table-column label="职业名称" align="center" prop="professionName" />
      <el-table-column label="职业大类" align="center" prop="professionCategory" />
      <el-table-column label="适用等级" align="center" prop="applicableLevels">
        <template #default="scope">
          <el-tag
            v-for="level in getApplicableLevelsArray(scope.row.applicableLevels)"
            :key="level"
            type="primary"
            class="mr-1"
          >
            {{ level }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="approvalStatus">
        <template #default="scope">
          <el-tag v-if="scope.row.approvalStatus === 0" type="info">待审核</el-tag>
          <el-tag v-else-if="scope.row.approvalStatus === 1" type="success">已通过</el-tag>
          <el-tag v-else-if="scope.row.approvalStatus === 2" type="danger">未通过</el-tag>
          <el-tag v-else-if="scope.row.approvalStatus === 3" type="warning">审核中</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180px"
      >
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:profession:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['eval:profession:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      :total="total"
      :current-page="queryParams.pageNo"
      :page-size="queryParams.pageSize"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
    />
  </el-card>

  <!-- 表单弹窗：添加/修改 -->
  <ProfessionForm ref="formRef" @success="getList" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { EvalProfessionVO, EvalProfessionPageReqVO, getProfessionPage, deleteProfession, exportProfession } from '@/api/eval/profession'
import ProfessionForm from './ProfessionForm.vue'

/** 职业工种 列表 */
defineOptions({ name: 'EvalProfession' })

const message = ElMessage

const loading = ref(true) // 列表的加载中
const list = ref<EvalProfessionVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive<EvalProfessionPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  professionCode: undefined,
  professionName: undefined,
  professionCategory: undefined,
  approvalStatus: undefined,
  createTime: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getProfessionPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 分页页码改变 */
const handleCurrentChange = (page: number) => {
  queryParams.pageNo = page
  getList()
}

/** 分页大小改变 */
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  queryParams.pageNo = 1
  getList()
}

/** 处理适用等级显示 */
const getApplicableLevelsArray = (levels: string | string[]) => {
  if (Array.isArray(levels)) {
    return levels
  }
  if (typeof levels === 'string' && levels) {
    return levels.split(',').filter(level => level.trim())
  }
  return []
}

/** 格式化日期时间 */
const formatDate = (timestamp: number | string | Date) => {
  if (!timestamp) return ''

  let date: Date
  if (typeof timestamp === 'number') {
    // 如果是时间戳，需要判断是秒还是毫秒
    date = new Date(timestamp > 1000000000000 ? timestamp : timestamp * 1000)
  } else if (typeof timestamp === 'string') {
    date = new Date(timestamp)
  } else {
    date = timestamp
  }

  if (isNaN(date.getTime())) return ''

  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 发起删除
    await deleteProfession(id)
    message.success('删除成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await ElMessageBox.confirm('确定要导出职业工种数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    // 发起导出
    exportLoading.value = true
    const data = await exportProfession(queryParams)
    // 这里简化处理，实际项目中需要实现下载功能
    message.success('导出成功')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
